package com.vast.ui.component.providers;

import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.CheckboxCellEditor;
import org.eclipse.jface.viewers.ColumnViewer;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.swt.SWT;

import socketinterface.CommunicationManager;

import com.vast.ui.component.models.Io;

public class IoEditingSupport extends EditingSupport {
	private CellEditor editor;
	private int column;
	private int numberOfItemInLine;
	private CommunicationManager communicationManager;
	
	public IoEditingSupport(ColumnViewer viewer, int column, int numberOfItemInLine, CommunicationManager communicationManager) {
		super(viewer);
		// TODO Auto-generated constructor stub
		editor = new CheckboxCellEditor(null, SWT.CHECK | SWT.READ_ONLY);
		this.communicationManager = communicationManager;
		this.column    = column;
		this.numberOfItemInLine = numberOfItemInLine;
	}

	@Override
	protected boolean canEdit(Object element) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	protected CellEditor getCellEditor(Object element) {
		// TODO Auto-generated method stub
		return editor;
	}

	@Override
	protected Object getValue(Object element) {
		// TODO Auto-generated method stub
		Io io = (Io)element;
		return io.isChecked(column);
	}

	@Override
	protected void setValue(Object element, Object value) {
		// TODO Auto-generated method stub
		Io io = (Io)element;
		io.setChecked(this.column, ((Boolean) value).booleanValue());
		int no = io.getLine() * numberOfItemInLine + this.column;
		if(communicationManager.isEstablished()) {
			communicationManager.client.sendIoUpdate(no, ((Boolean) value).booleanValue());
		}
		getViewer().update(element, null);
	}

}
